package com.atguigu.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * projectName: day04_jdbc
 *
 * @author: 赵伟风
 * time: 2021/11/26 16:13
 * description:jdbc的事务操作
 *    todo
 *       sql的事务操作
 *         1.关闭自动提交 手动提交【提交和回滚】
 *            show variables like '%autocommit%' #关闭了自动提交只在当前连接有效！
 *            set autocommit = off;
 *            sql
 *            sql
 *            commit/rollback;
 *         2.主动开启一个事务  手动提交【提交和回滚】
 *            start transaction;
 *            sql
 *            sql
 *            sql
 *            commit/rollback;
 *       jdbc的事务操作
 *          jdbc基于的关闭自动提交
 *          connection默认自动提交事务
 *          connection.setAutoCommit(false);
 *          statement connection.preparedStatment(); sql
 *          statement connection.preparedStatment(); sql
 *          connection.commit() / rollback();
 *          注意： 一个事务的statement必须由同一个connection创建！
 *
 *
 */
public class JdbcTransaction {


    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///test1?rewriteBatchedStatements=true", "root", "root");

        //关闭自动提交
        connection.setAutoCommit(false);

        try {

            String sql_add = "update account set money = money + 100 where aname = 'zhaoweifeng'";

            PreparedStatement statement = connection.prepareStatement(sql_add);

            int i = statement.executeUpdate();
            System.out.println("赵伟峰 +钱 = " + i);

            String sql_sub = "update account set money = money - 100 where aname = 'chenlei'";
            PreparedStatement statement1 = connection.prepareStatement(sql_sub);

            int i1 = statement1.executeUpdate();
            System.out.println("陈磊 -钱 = " + i1);

            connection.commit();
        }catch (SQLException e){
            e.printStackTrace();
            connection.rollback();
        }

    }

}
